'use client'
import React, { useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom'
import { AnimatePresence, motion } from 'framer-motion'
import IconButton from '@/components/common/IconButton'
import { X } from 'lucide-react'
import { useKeyboardEvent } from '@react-hookz/web'

const Popup = ({ isOpen, onClose, children }) => {
  const containerRef = useRef(null)
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    const div = document.createElement('div')
    div.className = 'popup-container'
    containerRef.current = div
    document.body.appendChild(div)
    setMounted(true)
    return () => { document.body.removeChild(div) }
  }, [])

  useKeyboardEvent(
    true,
    (event) => { if (event.key === 'Escape' && isOpen) { onClose?.() } },
    undefined,
    [isOpen]
  )

  if (!mounted || !containerRef.current) return null

  return ReactDOM.createPortal(
    <AnimatePresence>
      {isOpen && (
        <motion.div className="fixed inset-0 z-50" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.2 }} > <motion.div
          className="absolute inset-0 bg-white/60 backdrop-blur-sm" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.3 }} onClick={onClose} />
          <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} transition={{ duration: 0.2 }} className="absolute top-4 right-4 z-50" >
            <IconButton className="rounded-full w-10 h-10 flex items-center justify-center bg-[#F1F1F1] cursor-pointer" onClick={onClose} > <X color="white" /> </IconButton>
          </motion.div>
          <motion.div className="absolute bottom-0 left-1/2 -translate-x-1/2 bg-white max-w-[1000px] w-[96%] h-[90vh] rounded-t-sm shadow overflow-y-auto border border-gray-300 z-40 scrollbar-hide" initial={{ y: '100%', opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: '100%', opacity: 0 }} transition={{ duration: 0.4, ease: 'easeOut' }} onClick={(e) => e.stopPropagation()} >
            <div className="p-6">{children}</div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>,
    containerRef.current
  )
}

export default Popup
